import { Breadcrumb, Card, Form,Input, Button, Select, Radio, Upload, message } from "antd"
import { PlusOutlined } from "@ant-design/icons"
import { Link, useNavigate, useSearchParams } from "react-router-dom"
import './index.scss'
import ReactQuill from 'react-quill'
import "react-quill/dist/quill.snow.css";
import { createArticleApi, getListApi, newArticleApi } from "@/apis/article";
import { useEffect, useState } from "react";
import useChannel from "@/hooks/useChannel"

const Publish = () => {
  // 获取频道列表数据
  const {channelsList} = useChannel()
  const navigate = useNavigate()
  // 获取表单数据
  const onfinish = (formData) => {
    // 检验封面类型imageType是否和实际的图片列表imageList数量相等
    if(imageList.length !== imageType) return message.warning('封面类型与图片数量不符')
    // 按照接口文档的形式处理收集到的表单数据
    const {title, content, channel_id} = formData
    const reqData = {
      title,
      content,
      cover: {
        type:imageType,
        images:imageList.map(item => {
          if(item.response){
            return item.response.data.url
          }else{
            return item.url
          }
        })
      },
      channel_id
    }
    if(articleId){
      // 有id调用更新接口
      newArticleApi({...reqData,id:articleId})
    }else{
      // 调用新增接口
      createArticleApi(reqData)
    }
    navigate('/article')
  }
  // 处理上传的照片
  const [imageList, setImageList] = useState([])
  const handleChange = (value) => {
    setImageList(value.fileList)
  }
  // 切换上传图片类型
  const [imageType, setImageType] = useState(0)
  const imageTypeChange = (e) => {
    setImageType(e.target.value)
  }
  // 通过路由传参的id 回显表单数据
  const [params] = useSearchParams()
  const articleId = params.get('id')
  // 定义表单实例
  const [form] = Form.useForm()
  useEffect(() => {
    // 定义回填函数
    const getList = async () => {
      const res = await getListApi(articleId)
      // 用于回显数据
      form.setFieldsValue({
        ...res.data,
        type:res.data.cover.type
      })
      // 回填图片列表
      setImageType(res.data.cover.type)
      // 显示图片
      setImageList(res.data.cover.images.map(url => {
        return {url}
      }))
    }
    if(articleId){
      getList()
    }
  },[articleId,form])
  return (
    <div className="publish">
      <Card title={
        // 面包屑：实现导航栏
        <Breadcrumb items={[
          { title:<Link to='/'>首页</Link> },
          // 有 id 就是导航栏编辑文字
          { title:`${articleId ? '编辑' : '发布'}文章` }
        ]}/>
      }>
        <Form validateTrigger='onBlur'
          // 定义表单中所有‘标签’所在的网格列数，决定标签在水平方向上占用空间
          labelCol={{ span: 4 }}
          // 定义输入项(如Input、Select等)所在网格列数
          wrapperCol={{ span: 16 }}
          // 控制表单属性初始值
          initialValues={{ type: 0 }}
          onFinish={onfinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              { required: true, message: '请输入标题！' },
            ]}
          >
            <Input size="large" placeholder="请输入文章标题" style={{width:400}}/>
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              { required: true, message: '请选择文章频道' },
            ]}
          >
            {/* 下拉菜单选择频道 */}
            <Select size="large" placeholder="请选择文章频道" style={{ width: 400 }} 
              options={ channelsList.map(item => ({
                value:item.id, label:item.name
              }))}
            />
          </Form.Item>

          <Form.Item label='封面'>
              <Form.Item name='type'>
                <Radio.Group
                  block
                  onChange={imageTypeChange}
                  options={[
                    { value: 1, label: '单图' },
                    { value: 3, label: '三图' },
                    { value: 0, label: '无图' },
                  ]}
                />
              </Form.Item>
              <Upload
                action="http://geek.itheima.net/v1_0/upload"
                // 选择文件框的外观样式
                listType="picture-card"
                // 控制显示上传列表
                showUploadList
                onChange={handleChange}
                name="image"
                disabled={imageType > 0 ? false : true}
                maxCount={imageType}
                // 保证回显后图片能显示
                fileList={imageList}
              >
                <div style={{ marginTop: 8 }}>
                  {/* '＋'号图标 */}
                  <PlusOutlined />
                </div>
              </Upload>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true, message: '请输入文章内容！' },
            ]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item label={null}>
            {/* block 让按钮占据父容器的整个宽度 */}
            <Button type="primary" htmlType="submit" size="middle">
            发布文章
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish